<?php
function MostraArquivos(){
    $sql = "SELECT * FROM arquivos_remessa";
    $db = new db(config::$driver);
    $con = $db->conecta();
    $res = $db->query($sql, $con);
    $db->close($con);
    
    while($arq = $db->fetch_array($res)){
        echo "
        <tr>
            <td><a href='remessa/".$arq["arquivo"]."' target='_blanck'>".$arq["data"]."</a></td>
        </tr>";
    }
}

function numero($txt, $tam){
    if(strlen($txt) < $tam){
        
        $compl = "";
        $limite = $tam - strlen($txt);
        for($i = 0; $i < $limite; $i++){
            $compl .= "0";
        }
        return $compl.$txt;
        
    }else{
        return substr($txt, 0, $tam);
    }
}

function num_real($txt, $tam){
    $txt = str_replace(',', '.', $txt);
    if(!strstr(".", $txt)){
        $txt .= "00";
    }else{
        $t = explode('.', $txt);
        $txt = $t[0].substr($t[1], 0, 2);
    }
    
    if(strlen($txt) < $tam){
        
        $compl = "";
        $limite = $tam - strlen($txt);
        for($i = 0; $i < $limite; $i++){
            $compl .= "0";
        }
        return $compl.$txt;
        
    }else{
        return $txt;
    }
}

function alfa($txt, $tam){
    $what = array( 'ä','ã','à','á','â','ê','ë','è','é','ï','ì','í','ö','õ','ò','ó','ô','ü','ù','ú','û','À','Á','Â','Ã','Ä','È','É','Ê','Ì','Í','Ó','Ô','Ú','ñ','Ñ','ç','Ç');
    $by   = array( 'a','a','a','a','a','e','e','e','e','i','i','i','o','o','o','o','o','u','u','u','u','A','A','A','A','A','E','E','E','I','I','O','O','U','n','n','c','C');
    $txt = str_replace($what, $by, $txt);
    
    $esp = array(' ','_','-','.',',',);
    
    $txt = str_replace(array(chr(160),chr(194)), '', $txt);
    
    $tmp = strtoupper($txt);
    $txt = '';
    for($i = 0; $i < strlen($tmp); $i++){
        $c = substr($tmp, $i, 1);
        if((ord($c) >= 48 && ord($c <= 57)) || (ord($c) >= 65 && ord($c <= 90)) || (ord($c) >= 97 && ord($c <= 122)) || in_array($c, $esp)){
            $txt .= $c;
        }
    }
    
    $retorno = "";
    if(strlen($txt) > $tam){
        $retorno = substr($txt, 0, $tam);
        
    }else if(strlen($txt) < $tam){
        
        for($i = strlen($txt); $i < $tam; $i++){
            $txt .= " ";
        }
        $retorno = $txt;
        
    }else{
        $retorno = $txt;
    }
    return substr($retorno, 0, $tam);
}

function data($data){
    $data = substr($data, 0, 10);
    
    if(substr($data, 4, 1) == "-" && substr($data, 7, 1) == "-"){
        $d = explode('-', $data);
        $ano = $d[0];
        $mes = $d[1];
        $dia = $d[2];
    }else if(substr($data, 2, 1) == "/" && substr($data, 5, 1) == "/"){
        $d = explode('/', $data);
        $dia = $d[0];
        $mes = $d[1];
        $ano = $d[2];
    }
    
    if(strlen($dia) == 2 && strlen($mes) == 2 && strlen($ano) == 4){
        return $dia.$mes.substr($ano, 2);
    }else{
        return "000000";
    }
}

function limpaCPF($cpf){
    //return str_replace('.', '', str_replace('-', '', str_replace('/', '', $cpf)));
    return str_replace(array('.','-','/'), '', $cpf);
}



function GetMaxId(){
    $sql = "SELECT max(id) FROM arquivos_remessa";
    $db = new db(config::$driver);
    $con = $db->conecta();
    $res = $db->query($sql, $con);
    $db->close($con);
    
    $id = $db->fetch_array($res);
    return $id[0];
}

function AtualizaTransacao(){
    $sql = "UPDATE transacao SET remessa = 1 WHERE id IN(".$_SESSION["idsTransacao"].")";
    $db = new db(config::$driver);
    $con = $db->conecta();
    $res = $db->query($sql, $con);
    $db->close($con);
    
    return $res;
}

function CadastraArquivo($filename){
    $sql = "INSERT INTO arquivos_remessa(arquivo, data) VALUES('$filename', now())";
    $db = new db(config::$driver);
    $con = $db->conecta();
    $res = $db->query($sql, $con);
    $db->close($con);
    
    return $res;
}

function CarregaLinha($boleto, $data){
    $sql = "SELECT t.*, i.cpf FROM transacao t, inscrito_concurso ic, inscrito i
            WHERE t.valor_pago IS NULL AND t.id = ic.id AND ic.id_inscrito = i.id 
            AND t.remessa = 0 AND t.data_emissao like \"$data%\" AND t.id_boleto = ".$boleto->get_id();
    $db = new db(config::$driver);
    $con = $db->conecta();
    $res = $db->query($sql, $con);
    $db->close($con);

    $linha = null;
    while ($transacao = $db->fetch_array($res)){
        $linha[] = RegistroDetalhe($boleto, $transacao);
        if($_SESSION["idsTransacao"] != ''){
            $_SESSION["idsTransacao"] .= ",";
        }
        $_SESSION["idsTransacao"] .= $transacao["id"];
    }
    
    return $linha;
}

function GeraRemessa($boleto){
    $sql = "SELECT date(data_emissao) AS data FROM transacao
            WHERE remessa = 0 AND id_boleto = ".$boleto->get_id()."
            GROUP BY data";
    $db = new db(config::$driver);
    $con = $db->conecta();
    $res = $db->query($sql, $con);
    $db->close($con);
    
    while ($data = $db->fetch_array($res)){
        $_SESSION["sequencial"] = 1;
        $_SESSION["sequencial_lote"] = 0;
        $_SESSION["sequencial_registro_lote"] = 1;
        $_SESSION["valor_registro_lote"] = 0;
        $_SESSION["idsTransacao"] = '';
        
        // Gera o cabeçalho
        $conteudo = RegistroHeader($boleto)."\n";

        // Gera os detalhes
        $cnt = 0;
        $linha = CarregaLinha($boleto, $data[0]);
        foreach ($linha as $l){
            $conteudo .= $l."\n";
            $cnt++;
        }
        
        // Gera o Trailler
        $conteudo .= RegistroTrailler()."\n";

        // Gera o arquivo
        if($cnt > 0){
            AtualizaTransacao();
            
            $filename = date("YmdHis").".ret";
            $arq = fopen("remessa/$filename", "w");
            fwrite($arq, $conteudo);
            fclose($arq);
            
            CadastraArquivo($filename);
        }
    }
}
